<?php
    @include_once("conn.php");

    $key = $_GET["key"];
    $orderCol = $_GET["orderCol"];
    $orderType = $_GET["orderType"];
    $val = $_GET["val"];
    $pageIndex = $_GET["pageIndex"];

    if(!($orderCol&&$orderType&&$val&&$pageIndex)){
        argErr();
    }  

    $search = "select count(*) as allCount from `grade` where name like '%$key%'";
    $result = mysqli_query($conn,$search);
    $item = mysqli_fetch_assoc($result);
    $allcount = $item["allCount"];
    $maxPage = ceil($allcount/$val);

    if($pageIndex>$maxPage){
        $pageIndex = $maxPage;
    }

    if($pageIndex<1){
        $pageIndex = 1;
    }

    $skipNum = ($pageIndex-1)*$val;


    // $sql = "SELECT id,name,class,chinese,math,english,chinese+math+english as total from `grade` where name like '%$key%' ORDER BY $orderCol $orderType";
    $sql = "SELECT id,name,class,chinese,math,english,chinese+math+english as total from `grade` where name like '%$key%' ORDER BY $orderCol $orderType limit $skipNum,$val";
    $result = mysqli_query($conn,$sql);

    // $item = mysqli_fetch_assoc($result);
    $arr = array();
    while($item = mysqli_fetch_assoc($result)){
        $item["chinese"] = $item["chinese"]*1;
        $item["math"] = $item["math"]*1;
        $item["english"] = $item["english"]*1;
        $item["total"] = $item["total"]*1;

        array_push($arr,$item);
    }

    $obj = array();
    if(count($arr)>0){
        $obj["status"]=true;
        $obj["detail"]="ok";
        $obj["maxPage"] = $maxPage;   //最大页
        $obj["allCount"] = $allCount*1; //总数据(满足条件)
        $obj["list"]=$arr;
    }else{
        $obj["status"]=false;
        $obj["detail"]="暂无数据";
    }

    echo json_encode($obj);
?>